package com.zhiyou.app.config.oss;

import com.aliyuncs.exceptions.ClientException;
import com.zhiyou.app.common.exception.BizException;
import lombok.Getter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Map;

/**
 * oss配置
 */
@Slf4j
@Getter
@Configuration
@EnableConfigurationProperties(OssProperties.class)
@ConditionalOnProperty(prefix = "oss", value = "enabled", matchIfMissing = true)
public class OssConfig {
    private final OssProperties ossProperties;

    Map<String, String> env = System.getenv();

    @Autowired
    public OssConfig(OssProperties ossProperties) {
        this.ossProperties = ossProperties;
        if (!env.containsKey("OSS_ACCESS_KEY_ID") || !env.containsKey("OSS_ACCESS_KEY_SECRET")) {
            throw new BizException("请配置OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET");
        } else {
            ossProperties.setAccessKeyId(env.get("OSS_ACCESS_KEY_ID"));
            ossProperties.setAccessKeySecret(env.get("OSS_ACCESS_KEY_SECRET"));
            log.info("oss config success!");
        }
    }

    @Bean
    public OssUtil ossUtil() throws ClientException {
        return new OssUtil(ossProperties);
    }

}
